import React, { memo, forwardRef, useState } from 'react'
import { Select, Spin } from 'antd'
import {debounce} from '../utils/common'
import {getStoresAPI} from '../apis/store'

const {Option} = Select

const SelectStoreIDs = (props, ref) => {
  const {value, onChange} = props
  const [loading, setLoading] = useState(false)
  const [optionData, setOptionData] = useState([])
  const [err, setErr] = useState('未查询到符合的门店数据')

  const getStores = debounce(async (value) => {
    try {
      if (!value.trim()) return false
      setOptionData([]) // 先清空选项表
      setErr('未查询到符合的门店数据')
      setLoading(true)
      const {stores} = await getStoresAPI({keyword: value.trim()})
      console.log('SelectStoreIDs 查询到的门店数据: ', stores)
      if (stores) setOptionData(stores)
    } catch (e) {
      setErr(e.message)
    } finally {
      setLoading(false)
    }
  }, 1000)

  return (
    <Select
      ref={ref}
      mode="multiple"
      placeholder="请输入关键字选择门店"
      style={{width: '200px'}}
      value={value}
      onChange={onChange}
      notFoundContent={loading ? <Spin size="small" /> : <span>{err}</span>}
      filterOption={false}
      onSearch={getStores}
      allowClear
      maxTagCount={1}
    >
      {
        optionData.map(item => (
          <Option key={item.id} value={item.id}>({item.storeLevel}){item.name}-{item.cityName}</Option>
        ))
      }
    </Select>
  )
}

export default memo(forwardRef(SelectStoreIDs))
